#pragma once
#include <iostream>
#include <vector>
#include <mutex>
#include <fstream>
#include <string>
#include <cassert>
#include <algorithm>
#include <jsoncpp/json/json.h>
#include "oj_model.hpp"
#include "oj_view.hpp"
#include "../comm/util.hpp"
#include "../comm/httplib.h"
#include "../comm/log.hpp"

namespace ns_control
{
    using namespace std;
    using namespace ns_model;
    using namespace ns_log;
    using namespace ns_util;
    using namespace ns_view;
    using namespace httplib;

    class Machine
    {
    public:
        Machine()
            : _ip(""), _port(0), _load(0), _mtx(nullptr)
        {
        }
        ~Machine() {}

        // 获取主机的负载情况
        uint64_t Load()
        {
            uint64_t load = 0;
            if (_mtx)
                _mtx->lock();
            load = _load;
            if (_mtx)
                _mtx->unlock();
            return load;
        }

        // 增加主机的负载
        void IncLoad()
        {
            if (_mtx)
                _mtx->lock();
            _load++;
            if (_mtx)
                _mtx->unlock();
        }
        // 清除主机的负载
        void ClearLoad()
        {
            if (_mtx)
                _mtx->lock();
            _load = 0;
            if (_mtx)
                _mtx->unlock();
        }

        // 减少主机的负载
        void DecLoad()
        {
            if (_mtx)
                _mtx->lock();
            _load--;
            if (_mtx)
                _mtx->unlock();
        }

    public:
        string _ip;     // 提供编译服务主机的ip
        int _port;      // 提供编译服务主机的端口号
        uint64_t _load; // 主机的负载均衡系数
        mutex *_mtx;    // C++的mutex是禁止拷贝的,所以这里定义指针
    };

    const string server_machine = "./conf/service_machine.conf";

    class LoadBalance
    {
    public:
        LoadBalance()
        {
            assert(LoadConf(server_machine));
        }
        ~LoadBalance()
        {
        }

        bool LoadConf(const string &machine_conf)
        {
            ifstream in(machine_conf);
            if (!in.is_open())
            {
                // 没有成功打开文件
                LOG(FATAL) << " 打开machine_conf出错" << "\n";
                return false;
            }
            // 打开文件成功

            string line;
            while (getline(in, line))
            {
                vector<string> tokens;
                StringUtil::SpileString(line, &tokens, ":");
                if (tokens.size() != 2)
                {
                    LOG(WARNING) << "machine_conf文件,格式有误" << "\n";
                    continue;
                }
                // 成功切分
                Machine m;
                m._ip = tokens[0];
                m._port = stoi(tokens[1]);
                m._load = 0;
                m._mtx = new mutex();
                Online.push_back(Machines.size());
                Machines.push_back(m);
            }
            LOG(INFOR) << "成功加载machine_conf文件" << "\n";
            in.close(); // 记得关闭文件
            return true;
        }
        // 输出型：id
        // 输出型：Machine
        bool SmartChoice(int *id, Machine **m)
        {
            _mtx.lock();

            int OnlineNum = Online.size();
            if (OnlineNum == 0)
            {
                LOG(FATAL) << " 所有主机都离线了,请运维的老铁过来看看 " << "\n";
                _mtx.unlock();
                return false;
            }
            *id = Online[0];
            *m = &Machines[Online[0]];
            uint64_t min_load = Machines[Online[0]].Load();
            for (int i = 1; i < OnlineNum; i++)
            {
                uint64_t cur_load = Machines[Online[i]].Load();
                if (cur_load < min_load)
                {
                    min_load = cur_load;
                    *id = Online[i];
                    *m = &Machines[Online[i]];
                }
            }
            _mtx.unlock();
            return true;
        }

        // 将指定的一台主机进行离线
        void OfflineMachines(int witch)
        {
            _mtx.lock();
            for (auto iter = Online.begin(); iter != Online.end(); iter++)
            {
                if (*iter == witch)
                {
                    // 清除主机的负载系数
                    Machines[witch].ClearLoad();

                    Online.erase(iter);
                    Offline.push_back(witch);
                    break; //   直接break,迭代器失效不影响
                }
            }
            _mtx.unlock();
        }

        void OnlineMachines()
        {
            _mtx.lock();
            Online.insert(Online.end(), Offline.begin(), Offline.end());
            cout << "所有主机都上线啦！" << endl;
            _mtx.unlock();
        }

        void ShowMachines()
        {
            _mtx.lock();
            cout << "在线主机列表: ";
            for (const auto &id : Online)
            {
                cout << id << " ";
            }
            cout << endl;
            cout << "离线主机列表: ";
            for (const auto &id : Offline)
            {
                cout << id << " ";
            }
            cout << endl;
            _mtx.unlock();
        }

    private:
        // 记录所有编译服务的主机
        vector<Machine> Machines;
        // 记录在线主机的id列表
        vector<int> Online;
        // 记录离线主机的id列表
        vector<int> Offline;
        mutex _mtx;
    };

    class Control
    {
    public:
        Model _model;              // 提供后台数据
        View _view;                // 提供html渲染功能
        LoadBalance _load_balance; // 核心负载均衡器

    public:
        bool AllQuestions(string *html)
        {
            vector<Question> all;
            bool ret = true;
            if (_model.GetAllQuestions(&all))
            {
                // 对题目进行排序
                sort(all.begin(), all.end(), [](const Question &q1, const Question &q2)
                     { return q1.number < q2.number; });
                // 获取题目数据成功
                // 形成网页
                _view.AllExpandHtml(all, html);
            }
            else
            {
                *html = "获取题⽬失败, 形成题⽬列表失败";
                ret = false;
                // 获取题目信息失败
            }
            return ret;
        }

        bool Onequestion(const string &number, string *html)
        {
            Question q;
            bool ret = true;
            if (_model.GetOneQuestion(number, &q))
            {
                // 获取指定题目信息成功
                // 形成网页
                _view.OneExpandHtml(q, html);
            }
            else
            {
                *html = "指定题⽬: " + number + " 不存在!";
                ret = false;
            }
            return ret;
        }

        void RecoveryMachine()
        {
            _load_balance.OnlineMachines();
        }

        void Judge(const string &number, const string in_json, string *out_json)
        {
            // 0. 根据题⽬编号，直接拿到对应的题⽬细节
            Question q;
            _model.GetOneQuestion(number, &q);
            // 1. in_json进⾏反序列化，得到题⽬的id，得到⽤⼾提交源代码，input
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            string code = in_value["code"].asString();
            // 2. 重新拼接⽤⼾代码+测试⽤例代码，形成新的代码
            Json::Value compile_value;
            compile_value["input"] = in_value["input"].asString(); // 注意asString()和asCString()接口。
            compile_value["code"] = code + q.tail;
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit;
            Json::FastWriter writer;
            string compile_string = writer.write(compile_value);
            // 3. 选择负载最低的主机(差错处理)
            // 规则: ⼀直选择，直到主机可⽤，否则，就是全部挂掉
            while (true)
            {
                int id = 0;
                Machine *m = nullptr;
                if (!_load_balance.SmartChoice(&id, &m))
                {
                    LOG(ERROR) << "失败" << "\n";
                    break;
                }
                // 4. 然后发起http请求，得到结果
                Client cli(m->_ip, m->_port);
                m->IncLoad();
                LOG(INFOR) << "选出编译服务主机,详情: " << m->_ip << ":" << m->_port << " 负载系数:" << m->Load() << "\n";
                if (auto res = cli.Post("/compile_and_run", compile_string, "application/json;charset=utf-8"))
                {
                    LOG(INFOR) << "然后发起http请求" << "\n";
                    // http的状态码是200,才表明是成功的
                    if (res->status == 200)
                    {
                        // 5. 将结果赋值给out_json
                        *out_json = res->body;
                        m->DecLoad();
                        LOG(INFOR) << "请求和编译服务成功..." << "\n";
                        break;
                    }
                    m->DecLoad();
                }
                else // 请求失败
                {
                    LOG(ERROR) << " 当前请求的主机id: " << id << "详情: " << m->_ip << ":" << m->_port << " 可能已经离线" << "\n";
                    _load_balance.OfflineMachines(id);
                    _load_balance.ShowMachines();
                }
            }
        }
    };
}
